//
//  LoginController.m
//  RentTable
//
//  Created by mac on 2024/11/28.
//

#import "LoginController.h"
#import "AppDelegate.h"
#import "PrivacyTermsView.h"
#define LoginHeight 280
#define RegisterHeight  330

@interface LoginController ()

@property (nonatomic, strong) UIImageView *loginBackImageview;
@property (nonatomic, strong) UIImageView *topImageView;
@property (nonatomic, strong) UIImageView *loginImageView;
@property (nonatomic, strong) UIView *containView;
@property (nonatomic, strong) UIImage *origImage;
@property (nonatomic, strong) UIImage *flipImage;

@property (nonatomic, strong) UITextField *phoneNumberTextField;
@property (nonatomic, strong) UITextField *passwordTextField;
@property (nonatomic, strong) UITextField *confirmPasswordTextField;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *registerButton;

@property (nonatomic, strong) UIView *passwordAgainView;

@property (nonatomic, strong) UIImageView *passwordImageView;
@property (nonatomic, strong) UIImageView *confirmPasswordImageView;

@property (nonatomic, strong) UIButton *confirmButton;

@property (nonatomic, strong) UIButton *openHomeButton;

@property (nonatomic, assign) BOOL is_login;

@property (nonatomic, strong) PrivacyTermsView *privacyView;

@end

@implementation LoginController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"123");
    self.is_login = true;
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self setupUI];
}


- (void)setupUI {
    
    self.origImage = [UIImage imageNamed:@"登录账号"];
    self.flipImage = [UIImage imageWithCGImage:self.origImage.CGImage scale:self.origImage.scale orientation:UIImageOrientationUpMirrored];
    
    self.loginBackImageview = [[UIImageView alloc] initWithFrame:self.view.bounds];
    self.loginBackImageview.image = [UIImage imageNamed:@"启动页-bg"];
    [self.loginBackImageview setUserInteractionEnabled:true];
    [self.view addSubview:self.loginBackImageview];
    
    UIImageView *loginImageView = [UIImageView new];
    loginImageView.image = [UIImage imageNamed:@"注册账号"];
    [self.loginBackImageview addSubview:loginImageView];
    [loginImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(LoginHeight * scaleH);
    }];
    self.loginImageView = loginImageView;
    [self.loginImageView setUserInteractionEnabled:true];
    
    UIImageView *topImageView = [UIImageView new];
    topImageView.image = self.origImage;
    [self.loginBackImageview addSubview:topImageView];
    [topImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(LoginHeight * scaleH);
    }];
    self.topImageView = topImageView;
    [self.topImageView setUserInteractionEnabled:true];
    
    UIView *containView = [UIView new];
    [self.loginBackImageview addSubview:containView];
    [containView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(LoginHeight * scaleH);
    }];
    self.containView = containView;
    [self.containView setUserInteractionEnabled:true];
    
    self.loginButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.loginButton setTitle:@"登录账号" forState:UIControlStateNormal];
    [self.loginButton setTitleColor:myRGBHex(0x333333) forState:UIControlStateNormal];
    self.loginButton.titleLabel.font = [UIFont pingFangSCSemiboldWithSize:18];
    [self.loginButton addTarget:self action:@selector(loginButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [containView addSubview:self.loginButton];
    self.loginButton.selected = true;
    [self.loginButton.titleLabel sizeToFit];
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(17);
        make.leading.mas_equalTo(42);
        make.height.mas_equalTo(21);
    }];
    
    
    self.registerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.registerButton setTitle:@"注册账号" forState:UIControlStateNormal];
    [self.registerButton setTitleColor:myRGBHex(0xFFFFFF) forState:UIControlStateNormal];
    self.registerButton.titleLabel.font = [UIFont pingFangSCSemiboldWithSize:18];
    [self.registerButton addTarget:self action:@selector(registerButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [containView addSubview:self.registerButton];
    [self.registerButton.titleLabel sizeToFit];
    [self.registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(17);
        make.trailing.mas_equalTo(-53);
        make.height.mas_equalTo(21);
    }];
    
    UIView *phoneView = [self createTextFieldWithPlaceholder:@"请输入手机号" iconName:@"用户" secondIconName:nil];
    [containView addSubview:phoneView];
    phoneView.frame = CGRectMake(21, 109, spDeviceWidth-76, 40);
    self.phoneNumberTextField = [phoneView.subviews objectAtIndex:1];
    
    UIView *passwordView = [self createTextFieldWithPlaceholder:@"请输入密码" iconName:@"密码" secondIconName:@"显示"];
    [containView addSubview:passwordView];
    passwordView.frame = CGRectMake(21, 169, spDeviceWidth-76, 40);
    self.passwordTextField = [passwordView.subviews objectAtIndex:1];
    self.passwordImageView = [passwordView.subviews objectAtIndex:2];
    
    
    UIView *passwordAgainView = [self createTextFieldWithPlaceholder:@"请在此输入密码" iconName:@"密码" secondIconName:@"显示"];
    [containView addSubview:passwordAgainView];
    passwordAgainView.frame = CGRectMake(21, 229, spDeviceWidth-76, 40);
    self.confirmPasswordTextField = [passwordAgainView.subviews objectAtIndex:1];
    self.confirmPasswordImageView = [passwordAgainView.subviews objectAtIndex:2];
    self.passwordAgainView = passwordAgainView;
    [self.passwordAgainView setHidden:true];
    
    
    self.confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.confirmButton setTitle:@"登录" forState:UIControlStateNormal];
    [self.confirmButton setTitleColor:myRGBHex(0xFFFFFF) forState:UIControlStateNormal];
    self.confirmButton.titleLabel.font = [UIFont pingFangSCMediumWithSize:15];
    [self.confirmButton addTarget:self action:@selector(confirmButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.confirmButton];
    [self.confirmButton.titleLabel sizeToFit];
    self.confirmButton.frame = CGRectMake(44, 609 * scaleH, spDeviceWidth - 88, 44);
    self.confirmButton.layer.cornerRadius = 22;
    self.confirmButton.layer.masksToBounds = true;
    [CommondHandle gradientTheView:self.confirmButton bounds:self.confirmButton.bounds colors:@[myRGBHex(0xE375FF),myRGBHex(0xFF0AA1)] startPoint:CGPointMake(0, 0.5) endPoint:CGPointMake(1, 0.5) hasCornerRadius:22 shouldTakeBack:false];
    
    
    self.openHomeButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [self.openHomeButton setBackgroundImage:[UIImage imageNamed:@"登录进入"] forState:UIControlStateNormal];
    [self.openHomeButton setTitle:@"进入首页" forState:UIControlStateNormal];
    [self.openHomeButton setBackgroundColor:myRGBHex(0x333333)];
    self.openHomeButton.titleLabel.font = [UIFont pingFangSCMediumWithSize:15];
    [self.openHomeButton setTitleColor:myRGBHex(0xFFFFFF) forState:UIControlStateNormal];
    self.openHomeButton.layer.cornerRadius = 22;
    self.openHomeButton.layer.masksToBounds = true;
    [self.openHomeButton addTarget:self action:@selector(openHomeButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.openHomeButton];
    [self.openHomeButton.titleLabel sizeToFit];
    self.openHomeButton.layer.cornerRadius = 22;
    self.openHomeButton.layer.masksToBounds = true;
    [self.openHomeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(44);
        make.trailing.mas_equalTo(-30);
        make.size.mas_equalTo(CGSizeMake(80, 44));
    }];
    
    
    self.privacyView = [[PrivacyTermsView alloc] initWithFrame:CGRectMake((spDeviceWidth / 2.0 - 100 * scaleW), spDeviceHeight - 80 * scaleH, 200 * scaleW, 20 * scaleH)];
    [self.view addSubview:self.privacyView];
    [self.privacyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-70 * scaleH);
        make.centerX.mas_equalTo(0);
        make.size.mas_equalTo(CGSizeMake(200 * scaleW, 20 * scaleH));
    }];
    
}

- (UIView *)createTextFieldWithPlaceholder:(NSString *)placeholder
                                  iconName:(NSString *)iconName
                            secondIconName:(NSString *)secondIconName {
    UIView *containerView = [[UIView alloc] init];
    containerView.backgroundColor = [UIColor clearColor];
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:iconName]];
    iconImageView.translatesAutoresizingMaskIntoConstraints = NO;
    [containerView addSubview:iconImageView];
    
    UITextField *textField = [[UITextField alloc] init];
    textField.placeholder = placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    [containerView addSubview:textField];
    
    UIImageView *secondIconImageView = nil;
    if (secondIconName) {
        secondIconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:secondIconName]];
        secondIconImageView.translatesAutoresizingMaskIntoConstraints = NO;
        [containerView addSubview:secondIconImageView];
    }
    
    UIView *devideView = [UIView new];
    devideView.backgroundColor = myRGBHex(0xCCCCCC);
    [containerView addSubview:devideView];
    
    [iconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(containerView.mas_leading).offset(10);
        make.centerY.mas_equalTo(containerView.mas_centerY);
        make.width.mas_equalTo(16);
        make.height.mas_equalTo(16);
    }];
    
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(iconImageView.mas_trailing).offset(10);
        make.trailing.mas_equalTo(containerView.mas_trailing).offset(-10);
        make.centerY.mas_equalTo(containerView.mas_centerY);
        make.height.mas_equalTo(30);
    }];
    
    if (secondIconImageView) {
        [secondIconImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.trailing.mas_equalTo(-21);
            make.centerY.mas_equalTo(containerView.mas_centerY);
            make.width.mas_equalTo(20);
            make.height.mas_equalTo(20);
        }];
    }
    
    [devideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(22);
        make.trailing.mas_equalTo(-22);
        make.height.mas_equalTo(0.5);
        make.top.equalTo(iconImageView.mas_bottom).offset(12);
    }];
    
    return containerView;
}



- (void)loginButtonPressed:(UIButton *)sender {
    
    self.topImageView.image = self.origImage;
    [self updateMConstraints:true];
}

- (void)registerButtonPressed:(UIButton *)sender {
    
    self.topImageView.image = self.flipImage;
    [self updateMConstraints:false];
}

- (void)updateMConstraints:(BOOL)is_login {
    self.is_login = is_login;
    CGFloat height = is_login ? LoginHeight *scaleH : RegisterHeight *scaleH;
    [self.loginButton setTitleColor:myRGBHex(is_login ? 0x000000 : 0xFFFFFF) forState:UIControlStateNormal];
    [self.registerButton setTitleColor:myRGBHex(is_login ? 0xFFFFFF : 0x333333) forState:UIControlStateNormal];
    [self.passwordAgainView setHidden:(is_login)? true:false];
    self.passwordTextField.secureTextEntry = is_login ? false:true;
    self.confirmPasswordTextField.secureTextEntry = is_login ? false:true;
    self.phoneNumberTextField.text = @"";
    self.passwordTextField.text = @"";
    self.confirmPasswordTextField.text = @"";
    self.passwordImageView.image = [UIImage imageNamed:(is_login ? @"显示":@"密码1")];
    self.confirmPasswordImageView.image = [UIImage imageNamed:(is_login ? @"显示":@"密码1")];
    [self.confirmButton setTitle:(is_login? @"登陆":@"注册") forState:UIControlStateNormal];
    
    [self.loginImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(height);
    }];
    
    [self.topImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(height);
    }];
    
    [self.containView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(256 * scaleH);
        make.leading.mas_equalTo(16);
        make.trailing.mas_equalTo(-16);
        make.height.mas_equalTo(height);
    }];
}

- (void)confirmButtonPressed:(UIButton *)sender {
    
    
    
    NSString *account = [LocalDataManager loadDataForKey:UserAccount];
    NSString *password = [LocalDataManager loadDataForKey:UserPassword];
    
    NSString *userIphone = self.phoneNumberTextField.text;
    NSString *userPassword = self.passwordTextField.text;
    NSString *userConfirmPassword = self.confirmPasswordTextField.text;
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIWindow *window = appDelegate.window;
    UITabBarController *tabBarController = appDelegate.tabBarController;
    
    NSArray *inputsToCheck = self.is_login ? @[userIphone, userPassword] : @[userIphone, userPassword, userConfirmPassword];
    
    for (NSString *input in inputsToCheck) {
        if (![self isValidInput:input]) {
            return;
        }
    }
    
    if (!self.privacyView.isChecked) {
        [QLToast makeToast:@"请先阅读隐私政策并同意" toastType:QLToastTypeNormal toView:self.view];
        return;
    }
    
    if (self.is_login) {
        
        if ([userIphone isEqualToString:CeshiAccount] && [userPassword isEqualToString:CeshiMima]) {
            [LocalDataManager saveData:userIphone forKey:UserAccount];
            [LocalDataManager saveData:userPassword forKey:UserPassword];
            [LocalDataManager saveData:@"LogIn" forKey:LogStatu];
            window.rootViewController = tabBarController;
            return;
        }
        
        if ([account isEqualToString:userIphone] && [password isEqualToString:userPassword]) {
            [LocalDataManager saveData:@"LogIn" forKey:LogStatu];
            window.rootViewController = tabBarController;
        }else {
            [QLToast makeToast:@"用户名或者密码错误" toastType:QLToastTypeError toView:self.view];
        }
    }else {
        if ([userPassword isEqualToString:userConfirmPassword]) {
            window.rootViewController = tabBarController;
            [LocalDataManager saveData:userIphone forKey:UserAccount];
            [LocalDataManager saveData:userPassword forKey:UserPassword];
            [LocalDataManager saveData:@"LogIn" forKey:LogStatu];
        }else {
            [QLToast makeToast:@"密码不一致" toastType:QLToastTypeError toView:self.view];
        }
    }
}

- (BOOL)isValidInput:(NSString *)input {
    return input != nil && input.length > 0;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)openHomeButtonPressed:(UIButton *)sender {
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [appDelegate enterHome];
}

@end
